package org.robot.scm.platform.server.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.LocalCacheHelper;
import org.robot.scm.platform.server.common.LoggerHelper;

@Slf4j
@NoArgsConstructor
public class LogDownloadHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/download";
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("GET")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }

        Map<String, String> query = queryToMap(exchange.getRequestURI().getQuery());
        if (StringUtils.isBlank(query.get("key"))) {
            sendFailureResponse(exchange, "日志下载参数错误");
            return;
        }

        String fileKey = query.get("key");
        String message = LoggerHelper.getLogger(fileKey);
        try (OutputStream responseBody = exchange.getResponseBody()) {
            // 设置响应头，通知浏览器以附件形式下载文件
            exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
            exchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=\"" + fileKey + ".txt\"");
            exchange.sendResponseHeaders(200, message.getBytes(StandardCharsets.UTF_8).length);

            // 使用StringWriter和BufferedWriter构造文件内容
            StringWriter stringWriter = new StringWriter();
            BufferedWriter writer = new BufferedWriter(stringWriter);
            writer.write(message);
            writer.flush();
            writer.close();

            // 将内容写入到响应的输出流
            responseBody.write(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
            responseBody.flush();
            responseBody.close();
            exchange.close();

            // 移除日志
            LocalCacheHelper.remove(fileKey);
        }
    }

}
